<?php
/**
 * Created by PhpStorm.
 * User: Monkey
 * Date: 2021/10/13
 * Time: 11:27
 * Desc: 订单记录
 */
declare (strict_types=1);

namespace app\api\controller;

use app\api\base\controller\Base;
use app\api\validate\OrderValidate;
use app\extend\model\ProductData;

class Order extends Base
{
    /**
     * 持仓
     */
    public function getPositionAll()
    {
        $validate = new OrderValidate();
        $ret = $validate->scene('index')->check(input());
        if (!$ret) {
            return json(_E($validate->getError()));
        }

        $where = [
            ['uid','=',self::$UserInfo['id']],
            ['status','=',0]
        ];

        $list = [];
        $count = \app\extend\model\Order::where($where)->count();
        if($count > 0){
            $list = \app\extend\model\Order::where($where)->order(['id' => 'desc'])->select();

            foreach ($list as $value){

                $time_diff = strtotime($value->selltime) - time();
                $hours = floor($time_diff / 3600); // 计算小时
                $minutes = floor(($time_diff % 3600) / 60); // 计算分钟
                $seconds = $time_diff % 60; // 计算秒

                $value->new_price = ProductData::where([
                    ['product_id','=',$value->product_id]
                ])->value('price');

                // 格式化并输出时间差，确保时、分、秒都显示为两位数
                $value->time = sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
            }
        }

        return json([
            'code' => 0,
            'msg' => '获取成功',
            'count' => $count,
            'data' => $list,
        ])->send();
    }


    /**
     * 历史
     */
    public function getHistoryList()
    {
        $validate = new OrderValidate();
        $ret = $validate->scene('getHistoryList')->check(input());
        if (!$ret) {
            return json(_E($validate->getError()));
        }

        $page = input('page/d',1);
        $limit = input('limit/d',20);

        $where = [
            ['uid','=',self::$UserInfo['id']],
            ['status','=',1]
        ];

        $list = [];
        $count = \app\extend\model\Order::where($where)->count();
        if($count > 0){
            $list = \app\extend\model\Order::where($where)->order(['id' => 'desc'])->page($page)->limit($limit)->select();
        }

        return json([
            'code' => 0,
            'msg' => '获取成功',
            'count' => $count,
            'data' => $list,
        ])->send();
    }
}
